package com.horse.cloud.framework.security;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import net.minidev.json.JSONObject;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @create: Created by intelliJ IDEA18.1.3
 * @author: bing.Pan
 * @e-mail: 15923508369@163.com
 * @gmdate: 08/05/2019　11:41　星期三 (dd/MM/YYYY HH:mm)
 * @sidesc:
 */
public class JWTToken {

    private static final byte[] secret = "geiwodiangasfdjsikolkjikolkijswe".getBytes();


    /**
     * 创建token
     * @param payloadMap
     * @return
     * @throws JOSEException
     */
    private static String createToken(Map<String,Object> payloadMap) throws JOSEException {
        JWSHeader jwsHeader = new JWSHeader(JWSAlgorithm.HS256);
        Payload payload = new Payload(new JSONObject(payloadMap));
        JWSObject jwsObject = new JWSObject(jwsHeader, payload);
        JWSSigner jwsSigner = new MACSigner(secret);
        jwsObject.sign(jwsSigner);
        return jwsObject.serialize();
    }


    public static Map<String,Object> valid(String token) throws ParseException, JOSEException {
        JWSObject jwsObject = JWSObject.parse(token);
        Payload payload = jwsObject.getPayload();
        MACVerifier macVerifier = new MACVerifier(secret);
        Map<String, Object> resultMap = new HashMap<>();

        if (jwsObject.verify(macVerifier)) {
            JSONObject jsonObject = payload.toJSONObject();

            resultMap.put("data",jsonObject);
            if(jsonObject.containsKey("exp")){
                Long expTime = Long.valueOf(jsonObject.get("exp").toString());
                Long nowTime = new Date().getTime();
            }
        }
        return resultMap;

    }


    public static void main(String[] args) throws JOSEException, ParseException {
        Map<String,Object> map = new HashMap<>();
        map.put("id","id");
        map.put("name","name");
        String token = createToken(map);
        System.out.println("token=" + token);

        Map<String, Object> valid = valid(token);
        System.out.println(valid);


    }
}
